package com.gengzp.system.facade.impl;

import com.gengzp.common.enums.ServiceFrontBackTypeEnum;
import com.gengzp.common.model.serviceGovernance.entity.ServiceGovernance;
import com.gengzp.common.model.serviceGovernance.resp.SearchServiceGovernanceCountResp;
import com.gengzp.rpc.utils.RpcUtils;
import com.gengzp.system.facade.ServiceGovernanceFacade;
import com.gengzp.system.mapper.ServiceGovernanceMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName ServiceGovernanceFacadeImpl
 * @Description 服务治理模块门面层实现
 * @Author gengzp
 * @Date 2025/10/24 11:30
 */
@Service
public class ServiceGovernanceFacadeImpl implements ServiceGovernanceFacade {

    @Autowired
    private ServiceGovernanceMapper serviceGovernanceMapper;

    @Override
    public List<SearchServiceGovernanceCountResp> searchServiceGovernanceCount() {
        List<ServiceGovernance> serviceGovernanceList = serviceGovernanceMapper
                .selectGovernanceByFrontBackType(ServiceFrontBackTypeEnum.BACK_END.getCode());
        if (CollectionUtils.isEmpty(serviceGovernanceList)) {
            return Collections.emptyList();
        }

        return serviceGovernanceList.stream().map(v -> {
            SearchServiceGovernanceCountResp resp = new SearchServiceGovernanceCountResp();
            resp.setServiceName(v.getServiceName());
            resp.setServiceTitle(v.getServiceTitle());
            List<String> allAddressesByServiceName = RpcUtils.getAllAddressesByServiceName(v.getServiceName());
            resp.setHealthyInstanceCount(
                    CollectionUtils.isEmpty(allAddressesByServiceName) ? 0 : allAddressesByServiceName.size());
            return resp;
        }).collect(Collectors.toList());
    }

}
